#ifndef SINGLETON_H
#define SINGLETON_H

#include <JXQCore/JXQGlobal>
#include <JXQCore/JMutex>

// 永久的单例
#define J_PERMANENT_SINGLETON(Class) \
	public: \
		static Class &instance() \
		{ \
			static Class __unique_object__; \
			return __unique_object__; \
		} \
	private: \
		Class(); \
		~Class() {} \
		J_DISABLE_COPY(Class)

// 可销毁的单例
#define J_VOLATILE_SINGLETON_OBJECT(Class) \
	Class *Class::unique_object = nullptr; \
	std::mutex Class::unique_object_lock;

#define J_VOLATILE_SINGLETON(Class) \
	public: \
		static Class *unique_object; \
		static std::mutex unique_object_lock; \
		static Class &instance() \
		{ \
			if( unique_object == nullptr ) \
			{ \
				J_MUTEX_LOCKER(unique_object_lock); \
				if( unique_object == nullptr ) \
					unique_object = new Class(); \
			} \
			return *unique_object; \
		} \
		void destroyInstance() \
		{ \
			if( unique_object != nullptr ) \
			{ \
				static std::mutex __delete_lock__; \
				J_MUTEX_LOCKER(__delete_lock__) \
				if( unique_object != nullptr ) \
				{ \
					delete unique_object; \
					unique_object = nullptr; \
				} \
			} \
		} \
	private: \
		Class(); \
		~Class(); \
		J_DISABLE_COPY(Class)

// 进入main函数前构造单例对象
#define J_CREATE_SINGLETON(Class) \
	static J_DECL_USED Class &__init_unique_object__ = Class::instance();


#endif // SINGLETON_H
